<?php
namespace App\Models\Trade\Demand;

use App\Models\Model;

class DemandStatusModel extends Model
{

    const TABLENAME = 'tw_trade_demand_status';

    /**
     * 下架类型（自动下架）
     */
    const TYPE_VALIDED = 1;

    /**
     * 下架类型（用户下架）
     */
    const TYPE_USER = 2;

    /**
     * 下架类型（管理员下架）
     */
    const TYPE_ADMIN = 3;

    /**
     * 获取所有类型
     *
     * @return array
     */
    public static function getTypeList()
    {
        return array(
            self::TYPE_VALIDED,
            self::TYPE_USER,
            self::TYPE_ADMIN
        );
    }

    /**
     * 获取一条数据
     *
     * @param int $demandId            
     * @param array $fields            
     * @return \Illuminate\Support\Collection
     */
    public static function findByDemandId($demandId, array $fields = [])
    {
        $query = self::dbTable();
        if (count($fields)) {
            $query->select($fields);
        }
        
        return $query->where('demand_id', $demandId)->get();
    }

    /**
     * 添加一条数据
     *
     * @param number $demandId            
     * @param number $type            
     * @return false | 1 | 0 | id
     */
    public static function addItem($demandId, $type = self::TYPE_USER)
    {
        if (! $demandId || ! in_array($type, self::getTypeList())) {
            return false;
        }
        $data['type'] = $type;
        $data['updated'] = time();
        
        $item = self::findByDemandId($demandId)->shift();
        if ($item) {
            return self::dbTable()->where('id', $item['id'])->update($data);
        } else {
            $data['demand_id'] = $demandId;
            $data['created'] = $data['updated'];
            return self::dbTable()->insertGetId($data);
        }
    }
}
